<template>
    <a-input-search class="search-event" placeholder="请入事件类型" enter-button v-model:value="value" @search="onSearch">
    </a-input-search>
</template>
<script setup>
import { storeToRefs } from "pinia";
import { Query } from "assets/libs/utils/ES6Query.js";
import { ref, reactive, watch } from "vue";
import { useMapStore } from "stores/mapStore.js";
import { message } from "ant-design-vue";
/* 实例化useMapStore */
const mapStore = useMapStore();
/* 解构并响应式 */
const { map } = storeToRefs(mapStore);
const value = ref("");
// const eventFlag = ref(false);
const content = ref(null);
let info = null;
let position = null;
const container = ref(null);
// const formState = reactive({
//     eventId: "",
//     type: "",
//     level: "",
//     datetime: "",
//     address: "",
//     number: "",
//     user: "",
//     statu: "",
// });
var eventSource = new ol.source.Vector({
    wrapX: false,
});
/* 权限 */
// const usertype = reactive({
//     traffic: 1,
// });
// 创建用于标注查询到的事件的图层
// var docLayer = new ol.layer.Vector({
//     source: eventSource,
//     style: new ol.style.Style({
//         image: new ol.style.Icon({
//             // anchorOrigin: 'bottom-right',
//             // anchorXUnits: 'fraction',
//             // anchorYUnits: 'pixels',
//             // offsetOrigin: 'top-right',
//             // offset:[0,10],
//             //图标缩放比例
//             scale: 0.5,
//             //透明度
//             opacity: 1,
//             //图标的url
//             src: "/src/assets/images/标记瞄准.png",
//         }),
//     }),
// });
/**
   * 实现popup的html元素
   */
container.value = document.getElementById('popup');
content.value = document.getElementById('popup-content');
var closer = document.getElementById('popup-closer');
console.log(closer);
let popup = new ol.Overlay({
    //要转换成overlay的HTML元素
    element: container.value,
    //当前窗口可见
    autoPan: true,
    //Popup放置的位置
    positioning: "bottom-center",
    //是否应该停止事件传播到地图窗口
    stopEvent: false,
    autoPanAnimation: {
        //当Popup超出地图边界时，为了Popup全部可见，地图移动的速度
        duration: 250,
    },
});
let key; //标记地图点击事件
let mouseMoveKey //标记鼠标移动事件
function onSearch(searchValue) {
    console.log(1111111111);
    //创建图层对象, 将数据源添加到图层图像
    var eventLayer = new ol.layer.Vector({
        source: eventSource,
        style: new ol.style.Style({
            image: new ol.style.Circle({
                radius: 10,
                /* 填充色 */
                fill: new ol.style.Fill({
                    color: "#ff2d51",
                }),
                /* 描边 */
                stroke: new ol.style.Stroke({
                    color: "rgba(0,255,0,1)",
                    width: 1,
                }),
            }),
        }),
    });
    map.value.addOverlay(popup);
    //添加关闭按钮的单击事件（隐藏popup）
    closer.onclick = function () {
        //未定义popup位置
        popup.setPosition(undefined);
        //失去焦点
        closer.blur();
        /* 重置内容 */
        eventSource.clear();
        value.value = ""
        ol.Observable.unByKey(key); //移除点击事件
        ol.Observable.unByKey(mouseMoveKey); //移除鼠标移动事件
        map.value.removeLayer(eventLayer);
        content.value.style.width = "unset"
        // /* 移除点击事件 */
        // closer.onclick = null
        // closer = null
        // content.value = null
        // container.value = null
        return false;
    };

    map.value.addLayer(eventLayer);
    /* 当输入框清空是重置状态,关闭查询结果 */
    watch(value, (newValue) => {
        if (!newValue) {
            console.log("输入框空了");
            //未定义popup位置
            popup.setPosition(undefined);
            //失去焦点
            closer.blur();
            /* 重置内容 */
            eventSource.clear();
            value.value = ""
            ol.Observable.unByKey(key); //移除点击事件
            ol.Observable.unByKey(mouseMoveKey); //移除鼠标移动事件
            map.value.removeLayer(eventLayer);
            content.value.style.width = "unset"
            /* 移除点击事件 */
            // closer.onclick = null
            // closer = null
            // content.value = null
            // container.value = null
        }
    })
    //console.log(eventSource);
    //判断当前事件图层是否有要素数据
    if ((eventSource.revision_ = 0)) {
        eventSource.clear();
    }
    //获取关键字
    const keywords = value.value;
    if (!keywords) {
        message.warning("输入不能为空，请重新输入");
        return;
    }

    const sql = `事件类型 LIKE '%${keywords}%' OR 发生地点 LIKE '%${keywords}%' OR 处理状态 LIKE '${keywords}'`;
    //console.log(sql);
    Query.queryBySql({
        where: sql,
        service: {
            docName: "guanggu",
            //  事件在图层2
            layerId: 2,
        },
        callback: (e) => {
            if (e.TotalCount == 0) return message.warning("没有查询到相应的数据");
            //初始化Zondy.Format.PolygonJSON类
            var format = new Zondy.Format.PolygonJSON();
            //将MapGIS要素JSON反序列化为ol.Feature类型数组
            var features = format.read(e);

            //console.log("查询到的数据", features);
            eventSource.addFeatures(features);
            /* 将查询到的要素高亮标注显示， */
            map.value.addLayer(eventLayer);
        },
    });
    activeMap();
}
//点击地图事件查询
function activeMap() {
    key = map.value.on("click", handleMap); //激活地图点击事件
    mouseMoveKey = map.value.on("pointermove", handleToPointer); //激活地图点击事件
}
//当指向标注时改变鼠标光标状态
function handleToPointer(e) {
    var pixel = map.value.getEventPixel(e.originalEvent);
    var hit = map.value.hasFeatureAtPixel(pixel);
    map.value.getTargetElement().style.cursor = hit ? "pointer" : "";
}
function handleMap(e) {
    var feature = map.value.forEachFeatureAtPixel(
        e.pixel,
        function (feature, layer) {
            return feature;
        }
    );
    if (feature) {
        position = feature.getGeometry().flatCoordinates;
        popup.setPosition(position);
        /* 这个就可以拿到fid,拿到之后去空间数据库查这条数据 */
        Query.queryByFID({
            fid: feature.id_,
            service: {
                name: "guanggu",
                layerId: 2,
            },
            callback: (res) => {
                /**
   * 动态设置元素文本内容（兼容）
   */
                function setInnerText(element, text) {
                    if (typeof element.textContent == 'string') {
                        element.textContent = text;
                    } else {
                        element.innerText = text;
                    }
                }
                res = JSON.parse(JSON.stringify(res)).SFEleArray[0].AttValue;
                info = `
                <span style="width: 77px; display: inline-block; font-weight: 700;" >事件类型：</span style="width: 150px; display: inline-block;"><span>${res[1]}</span><br/>
                <span style="width: 77px; display: inline-block; font-weight: 700;" >事件等级：</span style="width: 150px; display: inline-block;"><span>${res[2]}</span><br/>
                <span style="width: 77px; display: inline-block; font-weight: 700;" >发生时间：</span style="width: 150px; display: inline-block;"><span>${res[3]}</span><br/>
                <span style="width: 77px; display: inline-block; font-weight: 700;" >发生地点：</span style="width: 150px; display: inline-block;"><span>${res[4]}</span><br/>
                <span style="width: 77px; display: inline-block; font-weight: 700;" >车牌号：</span style="width: 150px; display: inline-block;"><span>${res[5]}</span><br/>
                <span style="width: 77px; display: inline-block; font-weight: 700;" >驾驶员：</span style="width: 150px; display: inline-block;"><span>${res[6]}</span><br/>`;
                setTimeout(() => {
                    //新增标题元素存放监控器编号
                    var elementA = document.createElement('h3');
                    elementA.style.background = '#2196f3';
                    elementA.style.padding = '5px 10px';
                    elementA.style.height = '35px';
                    elementA.style.color = '#fff';
                    setInnerText(elementA, "查询结果");
                    // 新建的div元素添加A子节点
                    content.value.innerHTML = info;
                    content.value.style.width = "250px"
                    // content.value.appendChild(elementA);
                    content.value.insertBefore(elementA, content.value.childNodes[0]);
                }, 1);
            },
        });
    }
}
</script>
